import HttpRequest from "./http";
import { merge } from "lodash";
// import { getToken } from "../auth";
import { RequestCodeEnum, RequestMethodsEnum } from "@/enums/requestEnums";
import { useUserStore } from "@/stores/user";
import { useMessage } from "../message";

const message = useMessage();

const requestHooks = {
  requestInterceptorsHook(options, config) {
    const { urlPrefix, baseUrl, withToken, isAuth } = config;
    options.header = options.header ?? {};
    if (urlPrefix) {
      options.url = `${urlPrefix}${options.url}`;
    }
    if (baseUrl) {
      options.url = `${baseUrl}${options.url}`;
    }
    // const token = getToken();
    const userStore = useUserStore();
    if (withToken && !options.header.token) {
      options.header.token = userStore.token || "";
    }
    return options;
  },
  responseInterceptorsHook(response, config) {
    const { isTransformResponse, isReturnDefaultResponse, isAuth } = config;
    if (isReturnDefaultResponse) {
      return response;
    }
    if (!isTransformResponse) {
      if (response.data.code === 401) {
        return Promise.reject(response.data);
      }
      return response.data;
    }
    const { logout } = useUserStore();
    const { code, data, msg, show } = response.data;
    switch (code) {
      case RequestCodeEnum.SUCCESS:
        msg && show && message.toast(msg);
        return data;
      case RequestCodeEnum.FAILED:
        setTimeout(() => {
          message.toast(msg);
        }, 500);
        return Promise.reject(msg);
      case RequestCodeEnum.NETWORK_ERROR:
        message.toast(msg);
        return Promise.reject(msg);
      case RequestCodeEnum.TOKEN_INVALID:
        logout();
        message.toast(msg);
        return Promise.reject();
      case RequestCodeEnum.SERVICE_NEEOR:
        message.toast("服务错误，请稍后再试");
        return Promise.reject();
      case RequestCodeEnum.NOTFOUND:
        message.toast("找不到接口信息");
        return Promise.reject();
      default:
        return data;
    }
  },
  responseInterceptorsCatchHook(options, err) {
    if (options.method?.toUpperCase() == RequestMethodsEnum.POST) {
      console.log("🔥请求失败:", err, options);
    }
    return Promise.reject();
  },
};

let BASE_API;

// #ifdef H5
BASE_API = import.meta.env.VITE_APP_BASE_URL;
// #endif
// #ifdef MP-WEIXIN
BASE_API = import.meta.env.VITE_WECHAT_BASE_API;
// #endif
console.log(BASE_API, "-----------------", 123);
const defaultOptions = {
  requestOptions: {
    timeout: 10 * 1000,
    header: { version: "1.0.0" },
  },
  baseUrl: `${BASE_API || ""}`,
  isReturnDefaultResponse: false,
  isTransformResponse: true,
  urlPrefix: "",
  ignoreCancel: false,
  withToken: true,
  isAuth: false,
  retryCount: 0,
  retryTimeout: 300,
  requestHooks: requestHooks,
};

function createRequest(opt) {
  return new HttpRequest(merge(defaultOptions, opt || {}));
}
const request = createRequest();
export default request;
